/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode sort = head;
        while(fast != null) {
            sort = sort.next;
            if(fast.next != null) {
                fast = fast.next.next;
            } else{
                return null;
            }
            if(fast == sort) {
                break;
            }
        }
        if(fast != sort) {
            return null;
        } else{
            ListNode cur = head;
            while(cur != sort) {
                cur = cur.next;
                sort = sort.next;
            }
            return cur;
        }
        

     }
}